#include <algorithm>
#include <cstdio>
#include "InetSocketAddress.h"

InetSocketAddress::InetSocketAddress(const char* ip, int port)
{
	initializeInetSocketAddress(ip, port);
}

InetSocketAddress::InetSocketAddress(const string& ip, int port)
{
	initializeInetSocketAddress(ip.c_str(), port);
}

void InetSocketAddress::initializeInetSocketAddress(const char *ip, int port)
{
	// The in_addr structure represents an IPv4 Internet address
	unsigned long inaddr = ::inet_addr(ip);
	if (inaddr == INADDR_NONE) {
		static char buff[100];
		sprintf(buff, "%s %d (%s)", "InetSocketAddress(): INADDR_NONE", WSAGetLastError(), ip);
	}

	// Clear the sockaddr struct
	int bytes = sizeof(inetSockAddress);
	std::fill_n((char*)&inetSockAddress, bytes, 0);

	inetSockAddress.sin_family = AF_INET;
	inetSockAddress.sin_port = htons(port);
	inetSockAddress.sin_addr.s_addr = inaddr;
}

InetSocketAddress::InetSocketAddress(const InetSocketAddress &rhs)
{
	int bytes = sizeof(inetSockAddress);
	std::copy(
		(char *)(&(rhs.inetSockAddress)),
		(char *) (&(rhs.inetSockAddress)) + bytes,
		(char *) (&inetSockAddress));
}

InetSocketAddress::~InetSocketAddress(void)
{
}


InetSocketAddress InetSocketAddress::getByNameAndPort(const string& hostName, const string& port)
{
    return getByNameAndPort(hostName, atoi(port.c_str()));
}

InetSocketAddress InetSocketAddress::getByNameAndPort(const string& hostName, int port)
{
	hostent* host = ::gethostbyname(hostName.c_str());
	if (host == NULL) {
		// Should throw exception
	}

	::in_addr tmp = *(struct ::in_addr*) (host->h_addr);
    return InetSocketAddress(::inet_ntoa(tmp), port);
}